﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;
using System.IO;
using System.Xml.Linq;

namespace OneWord
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private int year;
        private int id;

        private int wordIndex = 0;// the index of words in one text

        private FileHandle fileHandle;

        private String[] fileNames; // the names of all file in the "Resouce" using for Lisbox
     
        private String currentWord;
        private String currentTranslate;

        private IEnumerable<XElement> xElement;

        public MainWindow()
        {
            InitializeComponent();
            MyInitialize();
        }
        private void MyInitialize()
        {
            fileHandle = new FileHandle();
            fileNames = Directory.GetFiles("../../Resouce", "*.txt");

            for (int i = 0; i < fileNames.Length; i++)
            {
                ListBoxItem item = new ListBoxItem();
                item.Content = System.IO.Path.GetFileNameWithoutExtension(fileNames[i]);
                listFileName.Items.Add(item);

            }

        }


        // exit app
        private void Exit()
        {
            Application.Current.Shutdown();
        }
        // add a text to list and to folder
        private void AddText()
        {
            String fileFullPath=null;
            String fileName = null;
            System.Windows.Forms.OpenFileDialog openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
            openFileDialog1.InitialDirectory = "c:\\";
            openFileDialog1.Filter = "txt files (*.txt)|*.txt";
            openFileDialog1.FilterIndex = 2;
            openFileDialog1.RestoreDirectory = true;
            if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                fileFullPath=openFileDialog1.FileName;
                fileName = Path.GetFileName(fileFullPath); 
                System.IO.File.Copy(fileFullPath, "../../Resouce/"+fileName, true);
            }

        }
        // select a word from a text
        private void SelectOne()
        {
            TextPointer potStart = flowDocumentReader.Selection.Start;
            TextPointer potEnd = flowDocumentReader.Selection.End;
            TextRange range = new TextRange(potStart, potEnd);
            labelWord.Content = range.Text;
        }
        //display next word from wordbook
        private void NextOne()
        {
            if (wordIndex < xElement.Count())
            {
                var tempElements = xElement;
                currentWord = tempElements.ElementAt(wordIndex).Element("word").Value;
                currentTranslate = tempElements.ElementAt(wordIndex).Element("trans").Value;

                DisplayWord(currentWord, currentTranslate);
                wordIndex++;
            }
            else
            {
                wordIndex = 0;
            }
            Color myRgbColor = new Color();
            myRgbColor = Color.FromRgb(0, 255, 0);
            fileHandle.MarkedWord(flowDocumentReader, flowDocument, currentWord, myRgbColor);       
        }
        private void DisplayWord(String txtWord, String txtTranslate) // display word
        {
            labelWord.Content = null;
            textBoxTranslate.Text = null;
            textBoxInput.Text = null;

            if (checkBoxEnglish.IsChecked.Value)
                labelWord.Content = txtWord;
            if (checkBoxChinese.IsChecked.Value)
                textBoxTranslate.Text = txtTranslate;

        }
        // add new word to workbook
        private void AddNewWord()
        {
            if ((labelWord.Content != null) && (textBoxTranslate.Text != null))
                fileHandle.InsertWord(labelWord.Content.ToString(), textBoxTranslate.Text, year, id);
            else
                MessageBox.Show("Both word and Translate are not empty");
        }
        // select a file from list of texts
        private void SelectText()
        {
            wordIndex = 0;
            int index = listFileName.SelectedIndex;
            String temp = (listFileName.SelectedItem as ListBoxItem).Content.ToString();
            string[] s = temp.Split(new char[] { '-' });
            year = System.Int32.Parse(s[0]);
            id = System.Int32.Parse(s[1]);

            if (fileHandle.LoadTextFile(flowDocument, fileNames[index]))
            {
                fileHandle.LoadXmlFile("../../Resouce/" + temp + ".xml");
                xElement = fileHandle.GetWords();
            }
        }
        // Spelling
        private void Spelling()
        {
            if (currentWord != null)
            {
                char[] ch = currentWord.ToCharArray();
                int iLength = textBoxInput.Text.Length;
                string sText = textBoxInput.Text;
                if (iLength > currentWord.Length)
                    textBoxInput.Foreground = Brushes.Red;
                else if (!sText.Equals(currentWord.Substring(0, iLength)))
                    textBoxInput.Foreground = Brushes.Red;
                else
                    textBoxInput.Foreground = Brushes.Black;
            }
        }
        // show Table of words
        private void TableWord()
        {
            WordTable wTable = new WordTable();
            wTable.Show();
        }
        private void textBoxInput_TextChanged(object sender, TextChangedEventArgs e)
        {
            Spelling();
        }


        // handle event
        private void Close_Click(object sender, RoutedEventArgs e) //close app
        {
            Exit();
        }



        private void AddWord_Click(object sender, RoutedEventArgs e)//add a new word to note
        {
            SelectOne();
        }


        private void Word_Click(object sender, RoutedEventArgs e)// get a new word from Text
        {
            NextOne();
        }



        private void buttonAddWord_Click(object sender, RoutedEventArgs e)
        {
            AddNewWord();
        }


        private void listFileName_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            SelectText();
        }



        private void Setting_Click(object sender, RoutedEventArgs e)
        {
            TableWord();
        }


        private void menuAdd_Click(object sender, RoutedEventArgs e)
        {
            AddText();
        }

        private void menuExit_Click(object sender, RoutedEventArgs e)
        {
            Exit();
        }

        private void menuTable_Click(object sender, RoutedEventArgs e)
        {
            TableWord();
        }

        private void menuList_Click(object sender, RoutedEventArgs e)
        {
            SelectText();
        }

        private void menuTest_Click(object sender, RoutedEventArgs e)
        {

        }

        private void meunEditWord_Click(object sender, RoutedEventArgs e)
        {

        }

        private void meunNewOne_Click(object sender, RoutedEventArgs e)
        {
            AddNewWord();
        }

        private void meunNextOne_Click(object sender, RoutedEventArgs e)
        {
            NextOne();
        }

        private void meunPreOne_Click(object sender, RoutedEventArgs e)
        {

        }

        private void menuAbout_Click(object sender, RoutedEventArgs e)
        {

        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {

        }

    }
}
